package cit.project.capeclear;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import com.android.dataframework.DataFramework;
import com.android.dataframework.Entity;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalPayment;

import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class ServiceActivity extends TabActivity  {
	
	private Bundle b;
	private TabHost mTabHost;
	
	private String serviceName = "";
	private String category = "";
	
	private byte[] imageAsBytes = null;
	private byte[] mapAsBytes = null;
	private String description = "";
	private String phone_number = "";
	private String opening_hours = "";
	private String duration = "";
	private String web = "";
	private String imageGallery = "";
	private String audioGallery = "";
	
	private String address = "";
	private String latitude = "";
	private String longitude = "";
	
	private float price = -1;
	private String paymentMail = "";
	private String paymentInfo = "";
	private int quantity = 1;
	
	private CheckoutButton launchPayment = null;
	private Payment payment = null;
	private static final int request = 1;
	private String resultTitle = "";
	private String resultInfo = "";
	private String resultExtra = "";
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.servicetabslayout);
        
        // Fills the bundle with the received 
        b = getIntent().getExtras();
        serviceName = b.getString("serviceName");
        category = b.getString("category");
        
        mTabHost = getTabHost();

		// Opening DataBase to work
		try {
			DataFramework.getInstance().open(this, "cit.project.capeclear");
		} catch (Exception e) {
			e.printStackTrace();
		}

    	setupTab(R.layout.infolayout, "Info");
    	setupTab(R.layout.locationlayout, "Location");
    	setupTab(R.layout.booklayout, "Book");

        
        mTabHost.setCurrentTab(1);
        mTabHost.setCurrentTab(2);
        
        
        loadService ();
		fillView ();
        
        mTabHost.setCurrentTab(0);
    }

    
    
    private void setupTab(final int tab_layout, final String tag) {
    	View tabview = createTabView(mTabHost.getContext(), tag);
            TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(new TabHost.TabContentFactory(){
  		      public View createTabContent (String tag) {
 		         return getLayoutInflater().inflate(tab_layout, null);}
    	});
    	mTabHost.addTab(setContent);
    }

    private static View createTabView(final Context context, final String text) {
    	View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
    	TextView tv = (TextView) view.findViewById(R.id.tabsText);
    	tv.setText(text);
    	return view;
    }    
    
    
    
    
    
    
    /*
     * Loads the information of the service from the SQLite database to
     * the variables of the class. 
     */
    private void loadService ()
    {
    	
		Entity ent = null;

		// Table SERVICES
		
		List<Entity> serviceList = DataFramework.getInstance().getEntityList("SERVICES", "TITLE = '" + serviceName +"'");
		Iterator<Entity> iter = serviceList.iterator();
		while (iter.hasNext()) {
			ent = (Entity)iter.next();
			
			description = ent.getString("DESCRIPTION");
			phone_number = ent.getString("PHONE");
			duration = ent.getString("DURATION");
			opening_hours = ent.getString("OP_HOURS");
			
			address = ent.getString("LOCATION");
			web = ent.getString("LINK");
			
			imageGallery = ent.getString("IMAGES");
			audioGallery = ent.getString("AUDIO");
			
		}
		
		
    	// Table GALLERY
        serviceList = DataFramework.getInstance().getEntityList("GALLERY", "TITLE = '" + serviceName +"'");
		iter = serviceList.iterator();
		
		if(iter.hasNext())
		{
			ent = (Entity)iter.next();
			String myString = ent.getString("PICTURE");			
			try {
				imageAsBytes = Base64.decode(myString.getBytes());
			} catch (IOException e) {
				imageAsBytes = null;
				e.printStackTrace();
			}			
		}
			
			
		// Table MAP
        serviceList = DataFramework.getInstance().getEntityList("MAP", "TITLE = '" + serviceName +"'");
		iter = serviceList.iterator();
		
		if(iter.hasNext())
		{
			ent = (Entity)iter.next();
			String myString = ent.getString("PICTURE");			
			try {
				mapAsBytes = Base64.decode(myString.getBytes());
			} catch (IOException e) {
				mapAsBytes = null;
				e.printStackTrace();
			}
			latitude = ent.getString("COORD_LAT");
			longitude = ent.getString("COORD_LONG");
		}
		
		
		// Table PAYPAL
        serviceList = DataFramework.getInstance().getEntityList("PAYPAL", "SHOP_NAME = '" + serviceName +"'");
		iter = serviceList.iterator();
		
		if(iter.hasNext())
		{
			ent = (Entity)iter.next();

			price = ent.getFloat("B_PRICE");
			paymentMail = ent.getString("MAIL");
			paymentInfo = ent.getString("B_INFO");
		}
		
    }
    
    
    /*
     * Builds the view of the service depending of the information stored
     * in the variables of the class.
     */
    private void fillView ()
    {
    	((TextView)findViewById(R.id.serviceName)).setText(serviceName);
    	
    	/****************
    	 *  INFO TAB
    	 ***************/

    	/**** Fills the image ****/
    	if(imageAsBytes != null)
    	{
    		ImageView image = (ImageView)this.findViewById(R.id.serviceImage);
    	    image.setImageBitmap(
    	            BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
    	    );     		
    	}
    	else
    		findViewById(R.id.serviceImage).setVisibility(View.GONE);

    	
    	/**** Fills the description ****/
    	if (description.length()>0)
    	{
    		TextView descriptiontv = (TextView)findViewById(R.id.description);
    		descriptiontv.setText(description);
    	}
    	else
    		findViewById(R.id.descriptionLayout).setVisibility(View.GONE);
    	
    	
    	/**** Fills the duration ****/
    	if (duration.length()>0)
    	{
    		TextView descriptiontv = (TextView)findViewById(R.id.duration);
    		descriptiontv.setText(duration);
    	}
    	else
    		findViewById(R.id.durationLayout).setVisibility(View.GONE);
    	
    	
    	/**** Fills the phone ****/
    	if (phone_number.length()>0)
    	{
    		TextView phonetv = (TextView)findViewById(R.id.phone);
    		phonetv.setText(phone_number);
    		
        	/* Call phone button */
        	((Button)findViewById(R.id.buttonCall)).setOnClickListener(new OnClickListener() {
        		  public void onClick(View v) {

        			  Intent i = new Intent(Intent.ACTION_DIAL);
        		        String p = "tel:" + phone_number;
        		        i.setData(Uri.parse(p));
        		        startActivity(i);
        		  }
        		});
    	}
    	else
    		findViewById(R.id.phoneLayout).setVisibility(View.GONE);
    	
    	
    	/**** Fills the webpage ****/
    	if (web.length()>0)
    	{
    		((TextView)findViewById(R.id.webAddress)).setText(web);
    		
    		
        	/* Webpage button */
        	((Button)findViewById(R.id.buttonWeb)).setOnClickListener(new OnClickListener() {
        		  public void onClick(View v) {

        			  
        			  if (!web.startsWith("http://"))
        				   web = "http://" + web;
        			  
        			  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(web)));
        			  
        		  }
        		});
    	}
    	else
    		findViewById(R.id.webLayout).setVisibility(View.GONE);
    	
    	
    	/**** Fills the opening hours ****/
    	if (opening_hours.length()>0)
    	{
    		((TextView)findViewById(R.id.hours)).setText(opening_hours);
    	}
    	else
    		findViewById(R.id.openingLayout).setVisibility(View.GONE);
    	
    	
    	/**** Fills the galleries ****/
    	if (!(imageGallery.length()>0) && !(audioGallery.length()>0)) //No galleries
    	{
    		findViewById(R.id.mediaLayout).setVisibility(View.GONE);
    	}
    	else
    	{
    		if (imageGallery.length()>0)
    		{
    	    	/* Image gallery button */
    	    	((Button)findViewById(R.id.imagesButton)).setOnClickListener(new OnClickListener() {
    	    		  public void onClick(View v) {

            			  if (!imageGallery.startsWith("http://"))
            				  imageGallery = "http://" + imageGallery;

            			  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(imageGallery)));
    	    		  }
    	    	});
    		}
    		else
    			findViewById(R.id.imageButtonLayout).setVisibility(View.GONE);

    		if (audioGallery.length()>0)
    		{
    	    	/* Audio gallery button */
    	    	((Button)findViewById(R.id.audioButton)).setOnClickListener(new OnClickListener() {
    	    		  public void onClick(View v) {
    	    			  
            			  if (!audioGallery.startsWith("http://"))
            				  audioGallery = "http://" + audioGallery;
           			  
            			  Bundle b = new Bundle();
            			  b.putString("webName", getString(R.string.audio));
						  b.putString("url", audioGallery);
						  Intent myIntent = new Intent(ServiceActivity.this, WebActivity.class);
						  myIntent.putExtras(b);
						  startActivity(myIntent);
            			  

    	    		  }
    	    	});
    		}
    		else
    			findViewById(R.id.audioButtonLayout).setVisibility(View.GONE);
    	
    	}


    	
    	/****************
    	 *  LOCATION TAB
    	 ***************/
    	
    	/**** Fills the map ****/
    	if(mapAsBytes != null)
    	{
    		ImageView image = (ImageView)this.findViewById(R.id.serviceMap);
    	    image.setImageBitmap(
    	            BitmapFactory.decodeByteArray(mapAsBytes, 0, mapAsBytes.length)
    	    );     		
    	}
    	else
    		findViewById(R.id.serviceMap).setVisibility(View.GONE);


    	/**** Fills the address ****/
    	if (address.length()>0)
    	{
    		((TextView)findViewById(R.id.addressText)).setText(address);
    	}
    	else
    		findViewById(R.id.addressText).setVisibility(View.GONE);
    	
    	/**** Sets the directions button ****/
    	if (latitude.length()>0 && longitude.length()>0)
    	{

        	/* directions button */
        	((Button)findViewById(R.id.buttonDirections)).setOnClickListener(new OnClickListener() {
        		  public void onClick(View v) {

        			  //String uri = "geo:"+ latitude + "," + longitude;
        			  String uri = "geo:0,0?q="+ latitude + "," + longitude + " (" + serviceName + ")";
  
        			  
        			  startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri)));
        			  
        		  }
        		});
    	}
    	else
    		findViewById(R.id.buttonDirections).setVisibility(View.GONE);
    	
    	
    	
    	/****************
    	 *  BOOK TAB
    	 ***************/
 

    	// If there is not payment information, hides the Booking Layout showing a message of
    	// no booking available.
    	if (price >= 0 && paymentMail.length()>0)
    	{
        	/**** Fills the payment information ****/
        	if (paymentInfo.length()>0)
        	{
        		((TextView)findViewById(R.id.bookDescription)).setText(paymentInfo);
        	}
        	else
        		findViewById(R.id.bookDescription).setVisibility(View.GONE);
    		
        	((TextView)findViewById(R.id.totalPrice)).setText(price + " Euros");
        	
        	((Button)findViewById(R.id.buttonMore)).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					quantity = Integer.parseInt(((TextView)findViewById(R.id.bookQuantity)).getText().toString());
					quantity++;
					((TextView)findViewById(R.id.bookQuantity)).setText(quantity+"");
					((TextView)findViewById(R.id.totalPrice)).setText((quantity*price)+" Euros");
					
				}
			});

        	((Button)findViewById(R.id.buttonLess)).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					quantity = Integer.parseInt(((TextView)findViewById(R.id.bookQuantity)).getText().toString());
					if (quantity>1)
						quantity--;
					((TextView)findViewById(R.id.bookQuantity)).setText(quantity+"");
					((TextView)findViewById(R.id.totalPrice)).setText((quantity*price)+" Euros");
					
				}
			});
        	

    		// Initialize the PayPal library. We'll do it in a separate thread 
            // because it requires communication with the server
    		// which may take some time depending on the connection strength/speed.
    		Thread libraryInitializationThread = new Thread() {
    			public void run() {
    				
    				payment = new Payment(ServiceActivity.this);
    				
    				payment.recipientMail = paymentMail;
    				payment.initLibrary();
    				
    				
    				
    				// The library is initialized so let's create our CheckoutButton and update the UI.
    				if (payment.isLibraryInitialized()) {
    					
    					launchPayment = payment.setupButton();
				        runOnUiThread( new Runnable()
				        {
				            @Override
				            public void run()
				            {
				            	findViewById(R.id.bookProgressBar).setVisibility(View.GONE);
				                ((LinearLayout)findViewById(R.id.PayPalButtonLayout)).addView(launchPayment);
				            }
				        } );

    					launchPayment.setOnClickListener(paypalListener);
    				}
    				else
    				{
				        runOnUiThread( new Runnable()
				        {
				            @Override
				            public void run()
				            {
				        		findViewById(R.id.bookLayout).setVisibility(View.GONE);
				        		
				        		((TextView)findViewById(R.id.textNoBooking)).setText("Library not initialized");
				        		((TextView)findViewById(R.id.textNoBooking)).setVisibility(View.VISIBLE);
				            }
				        } );
    					
    				}
    			}
    		};
    		libraryInitializationThread.start();

    	}
    	else
    	{
    		findViewById(R.id.bookLayout).setVisibility(View.GONE);
    		findViewById(R.id.textNoBooking).setVisibility(View.VISIBLE);
    	}
    }
    
    
    private OnClickListener paypalListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			//TODO			
			// Fills the details of the payment (already filled recipientMail)
			payment.paymentSubtotal = quantity*price+"";
			payment.storeName = serviceName + " store";
			payment.itemName = "Cape Clear App - " + serviceName + " booking.";
			payment.unitPrice = price+"";
			payment.quantity = quantity;
			payment.paymentMemo = "Payment made with Cape Clear App for Android. " +
					"Booking for " + quantity + " " + serviceName + " tickets. ";
			
			
			
			// Use our helper function to create the simple payment.
			PayPalPayment p = payment.simplePayment();	
			// Use checkout to create our Intent.
			Intent checkoutIntent = PayPal.getInstance().checkout(p, ServiceActivity.this, new ResultDelegate());
			// Use the android's startActivityForResult() and pass in our Intent. This will start the library.
			startActivityForResult(checkoutIntent, request);
			
		}
	};
    
    
    /*
     * Executed when the PayPal activity finishes.
     * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
     */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(requestCode != request)
    		return;

    	/**
    	 * If you choose not to implement the PayPalResultDelegate, then you will receive the transaction results here.
    	 * Below is a section of code that is commented out. This is an example of how to get result information for
    	 * the transaction. The resultCode will tell you how the transaction ended and other information can be pulled
    	 * from the Intent using getStringExtra.
    	 */
    	switch(resultCode) {
		case Activity.RESULT_OK:
			ArrayList <Item> v = new ArrayList<Item>();
			Item it = new Item(0, serviceName + " ticket", paymentInfo,
					"Booking", price, 0, serviceName);
			
			v.add(it);
			Bundle bundle = new Bundle();
			bundle.putString("paymentID", data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY));
			bundle.putString("quantity", quantity+"");
			bundle.putString("service", serviceName);
			Intent myIntent = new Intent(ServiceActivity.this, PaymentResult.class);
  			myIntent.putExtras(bundle);
  			//myIntent.putExtra("items", v);
  			myIntent.putParcelableArrayListExtra("items", v);
  			ServiceActivity.this.startActivity(myIntent);
			break;
		case Activity.RESULT_CANCELED:
			resultTitle = "CANCELED";
			resultInfo = "The transaction has been cancelled.";
			resultExtra = "";
	    	findViewById(R.id.bookLayout).setVisibility(View.GONE);
	    	findViewById(R.id.bookResultLayout).setVisibility(View.VISIBLE);
			break;
		case PayPalActivity.RESULT_FAILURE:
			resultTitle = "FAILURE";
			resultInfo = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
			resultExtra = "Error ID: " + data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
	    	findViewById(R.id.bookLayout).setVisibility(View.GONE);
	    	findViewById(R.id.bookResultLayout).setVisibility(View.VISIBLE);
		}

    	
    	
		((TextView)findViewById(R.id.resultTitle)).setText(resultTitle);
		((TextView)findViewById(R.id.resultInfo)).setText(resultInfo);
		((TextView)findViewById(R.id.resultExtra)).setText(resultExtra);
    	
    	launchPayment.updateButton();
    }    
}